﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RestSharp;
using WeiTalk.OAuth;
using System.ComponentModel;
using WeiTalk.Controls;
using WeiTalk.Interfaces.Sina;
using WeiTalk.SinaEntities.Status;
using System.Threading;
using Coding4Fun.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using System.Text.RegularExpressions;

namespace WeiTalk
{
    public partial class ContentDefaultPage : PhoneApplicationPage
    {
        string max_id = "0";
        DateTime Now = DateTime.Now;
        DateTime perTime = DateTime.Now;

        PullAndDownControl reflashControl = new PullAndDownControl();
        private double actuableOffset, validStartOffset;
        private bool mplStarted;
        private bool isUpdating = false;
        private string since_id = "0";
        string locker = "1";
        //bool isNextPage = false;
        bool isNoItem = false;
        const string isNoItemKey = "ContentDefaultPageIsNoItemKey";
        //const string isNextPageKey = "ContentDefaultPageIsNextPageKey";
        const string since_idKey = "ContentDefaultPageSince_IdKey";
        const string max_idKey = "ContentDefaultPageMax_IdKey";
        ImageViewer imageViewer = new ImageViewer();
        public ContentDefaultPage()
        {
            InitializeComponent();
            
        }

        private void AddWeiBoItems(List<WeiTalk.SinaEntities.Status.Content> data, bool isRefresh)
        {
            isNoItem = (data.Count == 1 && max_id != "0");
            if (data == null || data.Count == 0 || isNoItem)
            {
                lock (locker)
                {
                    isUpdating = false;
                }
                WeiBoUtility.ShowToast("休息一下吧，没有新的微博。");
                Dispatcher.BeginInvoke(() =>
                {
                    ResetPullControl();
                });
                if (spContent.Children.Count == 2)
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        spContent.Children.Remove(reflashControl);
                    });
                }
                return;
            }

            Dispatcher.BeginInvoke(() =>
            {
               spContent.Children.Remove(reflashControl);
            });

            int index = 0;
            if (!isRefresh)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    if (!(spContent.Children[spContent.Children.Count - 1] is PullAndDownControl))
                    {
                        spContent.Children.RemoveAt(spContent.Children.Count - 1);
                    }
                });
            }
            int refreshIndex = 1;
            foreach (Content item in data)
            {
                if (since_id == "0" ||(index == 0 && isRefresh))
                {
                    since_id = item.ID;
                }
                index++;

                max_id = item.ID;

                WeiBoControl control = new WeiBoControl();
                control.Name = String.Format("{0}_{1}", since_id, Guid.NewGuid().ToString());

                control.Click += new ClickEventHandler(WeiBoClick);
                control.ThumbnailPicClick +=new ImageClickEventHandler(ThumbnailPicClick);
                control.RetweetedThumbnailPicClick += new ImageClickEventHandler(ThumbnailPicClick);
                control.Text = item.Text;
                control.CreatedAt = item.CreatedAt;
                control.UserName = item.User.Name;
                control.OriginalPic = item.OriginalPic;
                try
                {
                    WeiBoUtility.RetrieveImage(item.User.ProfileImageUrl, (s) =>
                    {
                        BitmapImage bi = new BitmapImage();
                        bi.SetSource(s);
                        bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        control.ProfileImageUrl = bi;

                    }, Dispatcher.BeginInvoke);
                }
                catch { }
                control.Source = item.Source;
                control.CommentCount = item.CommentsCount.ToString();
                control.RepostsCount = item.RepostsCount.ToString();
                control.Id = item.ID;
                control.UserId = item.User.ID;
                if (item.RetweetedStatus != null)
                {
                    control.RetweetedId = item.RetweetedStatus.ID;
                    control.RetweetedContent = item.RetweetedStatus.Text;
                    control.RetweetedOriginalPic = item.RetweetedStatus.OriginalPic;
                    if (item.RetweetedStatus.User != null)
                    {
                        control.RetweetedUserId = item.RetweetedStatus.User.ID;
                        control.RetweetedUserName = item.RetweetedStatus.User.Name;
                        control.RetweetedCreateAt = item.RetweetedStatus.CreatedAt;
                    }
                    if (!String.IsNullOrEmpty(item.RetweetedStatus.ThumbnailPic))
                    {
                        try
                        {
                            control.RetweetedThumbnailPic = item.RetweetedStatus.ThumbnailPic;
                        }
                        catch { }
                    }

                    control.RetweetedSource = item.RetweetedStatus.Source;
                    control.RetweetedRepostsCount = item.RetweetedStatus.RepostsCount.ToString();
                    control.RetweetedCommentCount = item.RetweetedStatus.CommentsCount.ToString();
                }

                if (!String.IsNullOrEmpty(item.ThumbnailPic))
                {
                    try
                    {
                        control.ThumbnailPic = item.ThumbnailPic;
                    }
                    catch { }
                }

                Dispatcher.BeginInvoke(() =>
                  {
                      if (!isRefresh)
                      {
                          spContent.Children.Add(control);
                      }
                      else
                      {
                          spContent.Children.Insert(refreshIndex, control);
                          refreshIndex++;
                      }
                  });
            }
            Dispatcher.BeginInvoke(() =>
            {
                if (data.Count > 0)
                {
                    spContent.Children.Add(reflashControl);
                }
                //如果有更新，需要重置刷新控件
                ResetPullControl();
                WeiBoUtility.ShowToast(String.Format("你有{0}条更新.", data.Count));
            });
            lock (locker)
            {
                isUpdating = false;
            }
        }

        private void WeiBoClick(object sender, EventArgs e)
        {
            WeiBoControl control = (WeiBoControl)sender;
            control.sbSelected.Begin();
            control.sbSelected.Completed += (s, ev) =>
            {
                WeiBoShow.ParentControl = control;
                NavigationService.Navigate(new Uri("/WeiBoShow.xaml", UriKind.Relative));

            };
        }

        private void ThumbnailPicClick(object sender, ImageEventArgs e)
        {
            ApplicationBarIconButton mibtnLoading = FindLoadingButton();
            if (mibtnLoading == null)
            {
                return;
            }
            WeiBoUtility.ShowToast("正在下载图片...");
            WeiBoControl control = (WeiBoControl)sender;
            mibtnLoading.IsEnabled = false;
            WeiBoUtility.RetrieveImageByOne(e.ImageUrl, s =>
            {
                mibtnLoading.IsEnabled = true;
                mibtnLoading.Text = Constant.loadedMsg;
                imageViewer.Source = s;
                imageViewer.Control = control;
                imageViewer.IsReady = true;
                imageViewer.IsGif = Regex.IsMatch(e.ImageUrl, ".gif$", RegexOptions.IgnoreCase);
                WeiBoUtility.ShowToast("下载完成,点击查看...");
                this.ApplicationBar.Mode = ApplicationBarMode.Default;
            }, Dispatcher.BeginInvoke);
        }

        private ApplicationBarIconButton FindLoadingButton()
        {
            foreach (object button in this.ApplicationBar.Buttons)
            {
                if (button is ApplicationBarIconButton &&
                    (((ApplicationBarIconButton)button).Text == Constant.loadingMsg ||
                    ((ApplicationBarIconButton)button).Text == Constant.loadedMsg))
                {
                    return (ApplicationBarIconButton)button;
                }
            }
            return null;
        }

        private void ResetPullControl()
        {
            pullAndDownControl.Margin = new Thickness(0, -50, 0, 20);
            pullAndDownControl.Busy = false;
            pullAndDownControl.Ready = false;
        }

        private void UpdateFriends_TimeLine(bool update, bool isNextPage = false)
        {
            if (isUpdating)
            {
                return;
            }
            var client = new RestClient();
            StatusAPIs status = new StatusAPIs(client);
            string sinceId = update ? since_id : "0";
            string maxId = update ? "0" : max_id;
            status.GetFriendsTimeLine((result) =>
            {
                if (result.Data == null) 
                {
                    WeiBoUtility.ShowToast("更新异常，请重试。");
                    return;
                }
                List<WeiTalk.SinaEntities.Status.Content> data = ((WeiTalk.SinaEntities.Status.Entity)result.Data).Statuses;

                AddWeiBoItems(data, update);

            }, 1, 0, sinceId, maxId, 0, 0);
        }

        private void mibtnRefresh_Click(object sender, EventArgs e)
        {
            pullAndDownControl.Busy = true;
            pullAndDownControl.Text = "正在更新...";
            pullAndDownControl.Margin = new Thickness(0, 0, 0, 20);
            svUserTimeLine.ScrollToVerticalOffset(0d);
            UpdateFriends_TimeLine(true,true);
        }

        private bool IsPageFirstLoaded()
        {
            return !State.ContainsKey(since_idKey) || State[since_idKey] == null;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsPageFirstLoaded())
            {
                reflashControl.Busy = true;
                reflashControl.Text = "更新数据...";
                spContent.Children.Add(reflashControl);
                UpdateFriends_TimeLine(false);

                ScrollViewerMonitor svm = new ScrollViewerMonitor(svUserTimeLine);
                svm.AtEnd += new EventHandler((s, ev) => {
                    if (!isNoItem)
                    {
                        UpdateFriends_TimeLine(false);
                    }
                });
            }
            else
            {
                since_id = State.ContainsKey(since_idKey) ? State[since_idKey] as string: "0";
                max_id = State.ContainsKey(max_idKey) ? State[max_idKey] as string : "0";
                isNoItem = State.ContainsKey(isNoItemKey) ? (bool)State.ContainsKey(isNoItemKey) : false;
                //isNextPage = State.ContainsKey(isNextPageKey) ? (bool)State[isNextPageKey] : false;
            }
            ResetLoadingControl();
            this.ApplicationBar.Mode = ApplicationBarMode.Minimized;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            State[since_idKey] = since_id;
            State[max_idKey] = max_id;
            State[isNoItemKey] = isNoItem;
            base.OnNavigatedFrom(e);
        }

        private void ResetLoadingControl()
        {
            imageViewer.IsReady = false;
            ApplicationBarIconButton mibtnLoading = FindLoadingButton();
            if (mibtnLoading == null)
            {
                return;
            }
            mibtnLoading.Text = Constant.loadingMsg;
            mibtnLoading.IsEnabled = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        private void svUserTimeLine_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            int count = spContent.Children.Count;

            //head
            if (actuableOffset > Constant.UpdateHeight && svUserTimeLine.VerticalOffset < 1)
            {
                pullAndDownControl.Busy = true;
                pullAndDownControl.Text = "正在更新...";
                pullAndDownControl.Margin = new Thickness(0, 0, 0, 20);
                UpdateFriends_TimeLine(true);
            }
        }

        private void svUserTimeLine_MouseMove(object sender, MouseEventArgs e)
        {
            //head capture startRelative
            if (svUserTimeLine.VerticalOffset < 1)
            {
                if (mplStarted)
                {
                    mplStarted = false;
                    validStartOffset = e.GetPosition(null).Y;
                }
                actuableOffset = e.GetPosition(null).Y - validStartOffset;
            }
            //tail
            if (svUserTimeLine.VerticalOffset == svUserTimeLine.ScrollableHeight)
            {
                if (mplStarted)
                {
                    mplStarted = false;
                    validStartOffset = e.GetPosition(null).Y;
                }
                actuableOffset = e.GetPosition(null).Y - validStartOffset;
            }
            if (svUserTimeLine.VerticalOffset <1)
            {
                pullAndDownControl.Busy = false;
                if (actuableOffset > Constant.UpdateHeight)
                {

                    pullAndDownControl.Ready = true;
                    pullAndDownControl.Text = "松手可以更新...";
                }
                else
                {
                    if (pullAndDownControl.Ready)
                    {
                        pullAndDownControl.Ready = false;
                    }
                    pullAndDownControl.Text = "下拉可以更新...";
                }
                
            }
        }

        private void svUserTimeLine_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            mplStarted = true;
        }

        private void ImageViewer_Click(object sender, EventArgs e)
        {
            if(imageViewer.IsReady)
            {
                ImageViewerPage.Source = imageViewer.Source;
                ImageViewerPage.ParentControl = imageViewer.Control;
                ImageViewerPage.IsGif = imageViewer.IsGif;
                NavigationService.Navigate(new Uri("/ImageViewerPage.xaml", UriKind.Relative));
            }
            ResetLoadingControl();
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            e.Cancel = MessageBox.Show("回到登录页面吗？", "注销", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel;
          
        }

        private void mibtnPeople_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PeoplePage.xaml", UriKind.Relative));
        }

        private void mibtnMessage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MessagePage.xaml", UriKind.Relative));
        }
    }

    
    public class ImageViewer
    {
        bool isReady = false;
        public bool IsReady{
            get{return isReady;} 
            set{isReady = value;}
        }
        public bool IsGif { get; set; }
        public Stream Source { get; set; }
        public WeiBoControl Control { get; set; }
    }
}